<?php
	/**
	* 
	*/
	include ("connection.php");

	class Project
	{
		var $projectId;
		var $projectName;
		var $projectDescription;
		var $images;
		var $projectStart;
		var $projectEnd;

		public function Project($projectId, $projectName, $projectDescription, $projectStart, $projectEnd, $images)
		{
			$this->projectId = $projectId;
			$this->projectName = $projectName;
			$this->projectDescription = $projectDescription;
			$this->projectStart = $projectStart;
			$this->projectEnd = $projectEnd;
			$this->images = $images;
		}

		public static function ConnectDB(){
			$mysqli = new connection();

			if ($mysqli->connect_errno) {
			    echo "Fallo al conectar a MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
			}
			
			return $mysqli;
		}

		public static function GetLoginScreenProjects(){
			$mysqli = self::ConnectDB();

			$result = $mysqli->query("SELECT p.ProjectId, p.ProjectName, p.ProjectDescription, p.ProjectStart, p.ProjectEnd, i.ImageId, i.ImageName, i.IsPortrait, i.Section FROM projects p LEFT JOIN images i ON p.ProjectId = i.ProjectId ORDER BY p.ProjectStart DESC");

			$projects = array();
			$project = null;

			if($result === FALSE) {
			    die(mysqli_error());
			}
			else{
				while(($row = mysqli_fetch_array($result))){
					if(is_null($project) || $project->projectId != $row["ProjectId"]){
						$project = new Project(
							$row["ProjectId"], 
							$row["ProjectName"], 
							$row["ProjectDescription"], 
							$row["ProjectStart"], 
							$row["ProjectEnd"], 
							array(
								(object)
								array(
									'ImageId' 		=> $row["ImageId"],
									'ImageName' 	=> $row["ImageName"],
									'IsPortrait'	=> $row["IsPortrait"],
									'Section' 		=> $row["Section"],
									'ProjectId' 	=> $row["ProjectId"],
									'ImageURL' 		=> '/server/php/files/' . $row["ImageName"],
									'ThumbnailURL' 	=> '/server/php/files/thumbnail/' . $row["ImageName"]
								)
							)
						);
						array_push($projects, $project);
					}
					else{
						array_push($project->images,
							(object)
								array(
									'ImageId' 		=> $row["ImageId"],
									'ImageName' 	=> $row["ImageName"],
									'IsPortrait' 	=> $row["IsPortrait"],
									'Section' 		=> $row["Section"],
									'ProjectId' 	=> $row["ProjectId"],
									'ImageURL' 		=> '/server/php/files/' . $row["ImageName"],
									'ThumbnailURL'	=> '/server/php/files/thumbnail/' . $row["ImageName"]
								)
						);
					}
				}
			}
			return $projects;			

		}

		public static function GetAllProjects(){
			$mysqli = self::ConnectDB();

			$result = $mysqli->query("SELECT p.ProjectId, p.ProjectName, p.ProjectDescription, p.ProjectStart, p.ProjectEnd, i.ImageId, i.ImageName, i.IsPortrait, i.Section FROM projects p LEFT JOIN images i ON p.ProjectId = i.ProjectId;");

			$projects = array();
			$project = null;

			if($result === FALSE) {
			    die(mysqli_error());
			}
			else{
				while(($row = mysqli_fetch_array($result))){
					if(is_null($project) || $project->projectId != $row["ProjectId"]){
						$project = new Project(
							$row["ProjectId"], 
							$row["ProjectName"], 
							$row["ProjectDescription"], 
							$row["ProjectStart"], 
							$row["ProjectEnd"], 
							array(
								(object)
								array(
									'ImageId' 		=> $row["ImageId"],
									'ImageName' 	=> $row["ImageName"],
									'IsPortrait'	=> $row["IsPortrait"],
									'Section' 		=> $row["Section"],
									'ProjectId' 	=> $row["ProjectId"],
									'ImageURL' 		=> '/server/php/files/' . $row["ImageName"],
									'ThumbnailURL' 	=> '/server/php/files/thumbnail/' . $row["ImageName"]
								)
							)
						);
						array_push($projects, $project);
					}
					else{
						array_push($project->images,
							(object)
								array(
									'ImageId' 		=> $row["ImageId"],
									'ImageName' 	=> $row["ImageName"],
									'IsPortrait' 	=> $row["IsPortrait"],
									'Section' 		=> $row["Section"],
									'ProjectId' 	=> $row["ProjectId"],
									'ImageURL' 		=> '/server/php/files/' . $row["ImageName"],
									'ThumbnailURL'	=> '/server/php/files/thumbnail/' . $row["ImageName"]
								)
						);
					}
				}
			}
			return $projects;
		}

		public static function DeleteProject(){
			$mysqli = self::ConnectDB();

		    $projectId = $_POST['projectId'];

		    $stmt = $mysqli->prepare("DELETE FROM images WHERE ProjectId = ?;");
			$stmt->bind_param("i", $projectId);
			$stmt->execute();
			$stmt->close();

			$stmt = $mysqli->prepare("DELETE FROM projects WHERE ProjectId = ?;");
			$stmt->bind_param("i", $projectId);
			$stmt->execute();
			$stmt->close();

		}

		public static function SaveProject(){
			$mysqli = self::ConnectDB();

			$projectId = $_POST['projectId'];

			if($projectId <= 0){
				$projectName = $_POST['projectName'];
				$projectDescription = $_POST['projectDescription'];
				$projectInsertedIds = explode(",", $_POST['projectInsertedIds']);
				$projectBegin = $_POST['datePickerBefore'];
				$projectEnd = $_POST['datePickerAfter'];

				$stmt = $mysqli->prepare("INSERT INTO  projects (ProjectName,ProjectDescription, ProjectStart, ProjectEnd) VALUES (?,?,?,?);");
				$stmt->bind_param("ssss", $projectName, $projectDescription, $projectBegin, $projectEnd);
				$stmt->execute();
				$projectId = $stmt->insert_id;
				$stmt->close();

				for($i = 0; $i < count($projectInsertedIds); $i++){
					$stmt = $mysqli->prepare("UPDATE images SET ProjectId = ? WHERE ImageId = ?;");
					$stmt->bind_param("ii", $projectId, $projectInsertedIds[$i]);
					$stmt->execute();
					$stmt->close();
				}
			}
			else{
				$projectName = $_POST['projectName'];
				$projectDescription = $_POST['projectDescription'];
				$projectInsertedIds = explode(",", $_POST['projectInsertedIds']);
				$projectBegin = $_POST['datePickerBefore'];
				$projectEnd = $_POST['datePickerAfter'];
				$portraitId = $_POST['portraitId'];
				$sections = explode(",", $_POST['sections']);

				$stmt = $mysqli->prepare("UPDATE projects SET ProjectName = ?, ProjectDescription = ?, ProjectStart = ?, ProjectEnd = ? WHERE ProjectId = ?;");
				$stmt->bind_param("ssssi", $projectName, $projectDescription, $projectBegin, $projectEnd, $projectId);
				$stmt->execute();
				$stmt->close();

				if(count($projectInsertedIds) > 0){
					$parameters = "?";
					$types = "ii";

					for($i = 1; $i < count($projectInsertedIds); $i++){
						$parameters .= ",?";
						$types .= "i";
					}

					array_push($projectInsertedIds, $projectId);

					$query = "DELETE FROM images WHERE ImageId NOT IN (" . $parameters .") AND ProjectId = ?;";
					$stmt = $mysqli->prepare($query);
					call_user_func_array('mysqli_stmt_bind_param', array_merge(array($stmt, $types), self::refValues($projectInsertedIds))); 
					$stmt->execute();
					$stmt->close();

					for($i = 0; $i < count($projectInsertedIds); $i++){
						$stmt = $mysqli->prepare("UPDATE images SET ProjectId = ? WHERE ImageId = ?;");
						$stmt->bind_param("ii", $projectId, $projectInsertedIds[$i]);
						$stmt->execute();
						$stmt->close();
					}

					//Update portrait image if it was changed
					if($portraitId != null && $portraitId > 0){
						$stmt = $mysqli->prepare("UPDATE images SET IsPortrait = 0 WHERE ProjectId = ?;");
						$stmt->bind_param("i", $projectId);
						$stmt->execute();
						$stmt->close();

						$stmt = $mysqli->prepare("UPDATE images SET IsPortrait = 1 WHERE ProjectId = ? AND ImageId = ?;");
						$stmt->bind_param("ii", $projectId, $portraitId);
						$stmt->execute();
						$stmt->close();
					}

					if($sections != null && count($sections) > 0){
						for($i = 0; $i < count($sections); $i++){
							$stmt = $mysqli->prepare("UPDATE images SET Section = ? WHERE ImageId = ?;");
							$stmt->bind_param("ii", $sections[$i], $projectInsertedIds[$i]);
							$stmt->execute();
							$stmt->close();
						}
					}
				}
			}
		}

		public static function refValues($arr){
		    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
		    {
		        $refs = array();
		        foreach($arr as $key => $value)
		            $refs[$key] = &$arr[$key];
		        return $refs;
		    }
		    return $arr;
		} 
	}
?>